package com.zhilianbao.leyaogo.ui.fragment.home;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bql.baseadapter.recycleView.QuickRcvAdapter;
import com.bql.utils.CheckUtils;
import com.bql.utils.EventManager;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.app.LeYaoGoApplication;
import com.zhilianbao.leyaogo.constants.IntentConfig;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.SupplierApi;
import com.zhilianbao.leyaogo.http.callback.JsonCallback;
import com.zhilianbao.leyaogo.http.callback.LoadingViewCallback;
import com.zhilianbao.leyaogo.model.response.home.ServiceCity;
import com.zhilianbao.leyaogo.model.response.home.SupplierInfo;
import com.zhilianbao.leyaogo.ui.activity.MainActivity;
import com.zhilianbao.leyaogo.ui.adapter.home.SwitchClientAdapter;
import com.zhilianbao.leyaogo.ui.fragment.base.RefreshAndLoadFragment;
import com.zhilianbao.leyaogo.utils.LocationHelper;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zlb.lxlibrary.service.LeXiuInitService;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * ClassName: SelectShopFragment <br>
 * Description: 客户切换Fragment<br>
 * Author: Cyarie <br>
 * Created: 2016/11/1 17:13 <br>
 * Update Time：<br>
 * Update Description：<br>
 */
public class SwitchSupplierFragment extends RefreshAndLoadFragment<SupplierInfo> {


    @BindView(R.id.tv_location)
    TextView mTvLocation;
    @BindView(R.id.tv_nearby_shop)
    TextView mTvNearbyShop;
    @BindView(R.id.iv_refresh)
    ImageView mIvRefresh;
    //    @BindView(R.id.ll_service_city)
    //    LinearLayout mLlServiceCity;
    private SwitchClientAdapter mSwitchClientAdapter;
    private String cityCode;//属于城市 来自数据字典AREA
    private boolean isFirstEnter;//是否第一次进入应用选择运营商
    @BindView(R.id.ll_all_service_city)
    LinearLayout mLlAllServiceCity;
    //    @BindView(R.id.tg_hot_city)
    //    TagGroup mTgHotCity;

    private String locationCity;
    //    private boolean hasClickServiceCity;//是否点击服务城市


    public static SwitchSupplierFragment getInstance(boolean isFirstEnter) {
        SwitchSupplierFragment switchSupplierFragment = new SwitchSupplierFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean(IntentConfig.FIRST_SELECT_SUPPLIER, isFirstEnter);
        switchSupplierFragment.setArguments(bundle);
        return switchSupplierFragment;
    }

    @Override
    public void onRcvItemClick(RecyclerView.ViewHolder holder, int position) {
        //        LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRcvLoadMore.getLayoutManager();
        //        for (int i = linearLayoutManager.findFirstVisibleItemPosition(); i < linearLayoutManager.findLastVisibleItemPosition(); i++) {
        //            View view = mRcvLoadMore.getLayoutManager().getChildAt(i);
        //            if (view != null) {
        //                ImageView tick = (ImageView) view.findViewById(R.id.iv_tick);
        //                if (tick != null) {
        //                    tick.setVisibility(i==position?View.VISIBLE:View.GONE);
        //                }
        //            }
        //
        //        }
        mSwitchClientAdapter.notifyDataSetChanged();
        Utils.putSupplierId(mList.get(position).getSupplierId());
        Utils.putRongyunId(mList.get(position).getStrVal1());
        LeXiuInitService.getInstance().onOperatorIdChange(mList.get(position).getSupplierId() + "");
        if (Utils.getUserLoginInfo() != null) {
            SupplierApi.addSupplierUser(mActivity, new JsonCallback<Object>(mActivity, false) {
                @Override
                public void onSuccess(Object o, Call call, Response response) {

                }
            });
        }
        if (isFirstEnter) {
            Utils.startActivity(mActivity, MainActivity.class);
            mActivity.finish();
            Utils.putLocation(Utils.getLocationWithoutSuffix(locationCity));
        } else {
            mActivity.finish();
            EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_SELECT_OPERATOR, Utils.getLocationWithoutSuffix(locationCity)));
        }
        Utils.clearDefaultAddress();//清除SharePreference的默认地址
        Utils.clearShoppingCartUnCheckId();//清除购物车未选中的商品id

    }

    @Override
    public QuickRcvAdapter<SupplierInfo> getAdapter() {
        return mSwitchClientAdapter;
    }

    @Override
    public RecyclerView.ItemDecoration getItemDecoration() {
        return null;
    }

    @Override
    public RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(mActivity);
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void loadDataList(int curPage, boolean isPullToRefresh) {
        if (cityCode != null) {
            SupplierApi.getSupplierList(mActivity, cityCode, 0, new RefreshAndLoadCallback<List<SupplierInfo>>(isPullToRefresh) {
                @Override
                public void errorLeftOrEmptyBtnClick(View v) {
                    loadDataList(1, false);
                }

                @Override
                public void onResultSuccess(List<SupplierInfo> list, @Nullable Response response, LoadingViewCallback callback) {
                    handleRefreshAndLoadListData(curPage, callback, list);
                }

                @Override
                public String emptyContent() {
                    return LeYaoGoApplication.getContext().getString(R.string.city_have_no_supplier);
                }
            });

        }
    }

    @Override
    protected void initToolbarHere() {
        initToolbar(getString(R.string.select_supplier));
        isFirstEnter = getArguments().getBoolean(IntentConfig.FIRST_SELECT_SUPPLIER, false);
    }


    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        mSwitchClientAdapter = new SwitchClientAdapter(mActivity, mList);
        mTvLocation.setText(getString(R.string.getting_location));
        LocationHelper.getInstance().getInstantAddress();
        //        getServiceCity();

    }


    //    /**
    //     * 获取服务城市
    //     */
    //    private void getServiceCity() {
    //        SupplierApi.getSupplierCityList(mActivity, "", new JsonCallback<List<ServiceCity>>(mActivity, false) {
    //            @Override
    //            public void onSuccess(List<ServiceCity> list, Call call, Response response) {
    //                mLlServiceCity.setVisibility(CheckUtils.isEmpty(list) ? View.GONE : View.VISIBLE);
    //                if (!CheckUtils.isEmpty(list)) {
    //                    List<String> cityList = new ArrayList<>();
    //                    for (ServiceCity serviceCity : list) {
    //                        cityList.add(serviceCity.getStrCity());
    //                    }
    //                    mTgHotCity.setTags(cityList);
    //                    mTgHotCity.setOnTagClickListener((position, text) -> {
    //                        //                        hasClickServiceCity = true;
    //                        //                        pop();
    //                        //                        EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_SELECT_CITY, text + getString(R.string.city_suffix)));
    //                        OkHttpUtils.getInstance().cancelTag(mActivity);
    //                        locationCity = text;
    //                        mTvNearbyShop.setText(getString(R.string.shop_nearby_format, text));
    //                        //                        if (mTvLocation != null) {
    //                        //                            mTvLocation.setText(text);
    //                        cityCode = list.get(position).getCity();
    //                        mSwitchClientAdapter.clear();
    //                        loadDataList(1, false);
    //                        //                        }
    //
    //                    });
    //                } else {
    //
    //                }
    //            }
    //        });
    //    }

    @Override
    public void onLoadMore() {

    }

    @Override
    public boolean canRefresh() {
        return false;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_switch_client;
    }

    @OnClick({R.id.ll_all_service_city, R.id.iv_refresh})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_all_service_city:
                start(SwitchCityFragment.getInstance());
                break;
            case R.id.iv_refresh:
                mTvLocation.setText(getString(R.string.getting_location));
                LocationHelper.getInstance().getInstantAddress();
                //                if (mTgHotCity != null && CheckUtils.isEmpty(mTgHotCity.getTags()))
                //                    getServiceCity();
                break;
        }
    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Override
    protected void onHandleEvent(EventManager eventManager) {
        super.onHandleEvent(eventManager);
        switch (eventManager.getEventCode()) {
            case LeEventCode.MSG_CODE_BAIDU_LOCATION_SUC:

                String location = (String) eventManager.getData();
                if (!CheckUtils.isEmpty(location) && mTvLocation != null) {
                    mTvLocation.setText(location);
                }
                cityCode = Utils.getCityCode(location);
                mSwitchClientAdapter.clear();
                locationCity = location;
                mTvNearbyShop.setText(getString(R.string.shop_in_service_format, location));
                loadDataList(1, false);
                break;

            case LeEventCode.MSG_CODE_BAIDU_LOCATION_FAILED:
                if (mTvLocation != null) {
                    mTvLocation.setText(getString(R.string.failed_re_get_location));
                }
                break;

            case LeEventCode.MSG_CODE_SELECT_CITY:
                ServiceCity serviceCity = (ServiceCity) eventManager.getData();
                if (serviceCity != null) {
                    //                    mTvLocation.setText((String) eventManager.getData());
                    locationCity = serviceCity.getStrCity();
                    mTvNearbyShop.setText(getString(R.string.shop_in_service_format, serviceCity.getStrCity()));
                    cityCode = serviceCity.getCity();
                    mSwitchClientAdapter.clear();
                    loadDataList(1, false);
                }

                break;
        }
    }

    @Override
    public void leftContainerClick() {
        if (isFirstEnter) {
            //            Bundle bundle = new Bundle();
            //            bundle.putBoolean(IntentConfig.FIRST_SELECT_SUPPLIER, true);
            //            Utils.startActivity(mActivity, MainActivity.class, bundle);
            XToastUtils.showShortToast(getString(R.string.please_select_supplier));
            return;
        }
        super.leftContainerClick();
        //        if (CheckUtils.isEmpty(Utils.getLocation())) {
        //            ThreadPool.postOnUiDelayed(() -> EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_LOCATION_BACK)), 100);
        //        }

    }

    @Override
    public boolean isSpringMode() {
        return true;
    }

}
